const express = require("express");
const axios = require("axios");

const API_PASSWORD = process.env.API_PASSWORD;
const URL = process.env.URL;
const MODEL = "4.0Ultra";
const USER = "123456";
const TIMEOUT = 60000;
const PORT = 10024;

const system = "你是一名全栈开发工程师，擅长前端开发、后端开发、数据库设计、服务器运维等。";

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/api/stream", async (req, res) => {
  const message = req.query.message || "";
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  res.setHeader("Access-Control-Allow-Origin", "*");

  const params = {
    model: MODEL,
    user: USER,
    messages: [
        {
            "role": "system",
            "content": system
        },
        {
            "role": "user",
            "content": message
        }
    ],
    stream: true,
  };

  const requestConfig = {
    headers: {
      Authorization: `Bearer ${API_PASSWORD}`,
      Accept: "text/event-stream",
      "Content-Type": "application/json",
    },
    responseType: "stream",
    timeout: TIMEOUT,
  };

  try {
    const response = await axios.post(URL, params, requestConfig);
    response.data.on("data", (chunk) => {
        //转为字符串
        let data = chunk.toString("utf8")
        if(data.includes('[DONE]')) return
        //JSON字符串
        data = data.startsWith('data: ') ? data.substring(6) : data;
        //解析对象
        data = JSON.parse(data);
        if(data.code !== 0) {
            console.error("消息异常", data.message);
            res.write(`data:${data.message}\n\n`);
            res.end();
        };
        // 内容
        const content = data.choices?.[0]?.delta?.content || "";
        res.write(`data:${JSON.stringify({ content })}\n\n`);
    });
    response.data.on("end", () => {
        res.write("data:[DONE]\n\n");
        res.end();
    });
    response.data.on("error", (error) => {
        console.error("接受异常", error.message);
        res.write(`data:{"error":"${error.message}"}\n\n`);
        res.end();
    });
  } 
  catch (error) {
    console.error("发送异常", error.message);
    res.write(`data:{"error":"${error.message}"}\n\n`);
    res.end();
  }
})

app.get("/", (req, res) => {
  res.send("Hello World!");
})

// 启动服务
app.listen(PORT, 'localhost', () => {
  console.log(`Server running at http://localhost:${PORT}`);
});